package com.tanhua.server.server;


import com.tanhua.autoconfig.template.HuanXinTemplate;
import com.tanhua.autoconfig.template.SmsTemplate;
import com.tanhua.dubbo.api.UserApi;
import com.tanhua.model.domian.User;
import com.tanhua.utils.Constants;
import com.tanhua.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class UserServer {

    @Autowired
    private SmsTemplate smsTemplate;

    @DubboReference
    private UserApi userApi;

    @Autowired
    private HuanXinTemplate huanXinTemplate;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private MqMessageService mqMessageService;

    public void sendCode(String phone) {
        //生成随机验证码
        //String s = RandomStringUtils.randomNumeric(6);
        //利用第三方发送短信验证码
        //smsTemplate.sendSms(phone, "123456");
        String s= "123456";
        //将验证码存入redis
        redisTemplate.opsForValue().set("CHECK_CODE_" + phone, s, Duration.ofMinutes(5));
        System.out.println("CHECK_CODE" + phone+"--------"+s);

    }

    /**
     * 登录，如果未注册过进入注册页面
     * @param mobile
     * @param code
     * @return
     */
    public Map loginVerification(String mobile, String code) {
        //1. 从Redis中获取验证码
        String redisCode = redisTemplate.opsForValue().get("CHECK_CODE_" + mobile);
        System.out.println("CHECK_CODE_" + mobile);
        System.out.println(redisCode);
        //2. 校验验证码
        if(StringUtils.isEmpty(code) || !code.equals(redisCode)) {
            throw new RuntimeException("验证码校验失败");
        }
        //比对通过 , 删除验证码
        redisTemplate.delete("CHECK_CODE_" + mobile);

        //3. 判断用户是否注册
        boolean isNew = false;
        User user = userApi.findByMobile(mobile);
        String type = "0101";//登录
        if (user == null) {
            type = "0102";//注册
            user = new User();
            user.setMobile(mobile);
            user.setPassword(DigestUtils.md5Hex("123456"));
            Long id = userApi.save(user);
            user.setId(id);
            isNew = true;

            //注册环信用户
            String hxUser = "hx"+user.getId();
            Boolean create = huanXinTemplate.createUser(hxUser, Constants.INIT_PASSWORD);
            if(create) {
                user.setHxUser(hxUser);
                user.setHxPassword(Constants.INIT_PASSWORD);
                userApi.update(user);
            }

        }

        mqMessageService.sendLogMessage(user.getId(),type,"user",null);

        //4. 登录成功, 生成token
        Map<String, Object> tokenMap = new HashMap<String, Object>();
        tokenMap.put("id", user.getId());
        tokenMap.put("mobile", mobile);
        String token = JwtUtils.getToken(tokenMap);

        //5. 封装数据返回
        Map<String, Object> result = new HashMap<>();
        result.put("token", token);
        result.put("isNew", isNew);

        return result;
    }
}
